package com.lekang.system.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

import com.lekang.common.utils.DateUtils;
import com.lekang.common.utils.SecurityUtils;
import com.lekang.system.domain.*;
import com.lekang.system.mapper.*;
import com.lekang.system.service.IBillDetailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lekang.system.service.IBillService;

/**
 * 入账列表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-13
 */
@Service
public class BillServiceImpl implements IBillService 
{
    private static final Logger log = LoggerFactory.getLogger(BillServiceImpl.class);

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private CheckInManagementMapper checkInManagementMapper;
    
    @Autowired
    private NursingItemMapper nursingItemMapper;
    
    @Autowired
    private RoomTypeMapper roomTypeMapper;

    @Autowired
    private BalanceMapper balanceMapper;

    @Autowired
    private ElderlyMapper elderlyMapper;

    @Autowired
    private IBillDetailService billDetailService;

    @Autowired
    private NursingLevelMapper nursingLevelMapper;

    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入账列表
     * 
     * @param id 入账列表主键
     * @return 入账列表
     */
    @Override
    public Bill selectBillById(Long id)
    {
        // 1. 查询账单基本信息（已包含老人、床位、房间、房间类型、创建人的关联数据）
        Bill bill = billMapper.selectBillById(id);
        if (bill == null) {
            return null;
        }
        
        // 2. 根据老人ID查询入住信息
        if (bill.getElderlyId() != null) {
            CheckInManagement queryParam = new CheckInManagement();
            queryParam.setElderlyId(bill.getElderlyId());
            List<CheckInManagement> checkInList = checkInManagementMapper.selectCheckInManagementList(queryParam);
            
            if (checkInList != null && !checkInList.isEmpty()) {
                CheckInManagement checkInManagement = checkInList.get(0);
                bill.setCheckInManagement(checkInManagement);
                
                // 3. 根据入住管理中的护理等级ID查询护理等级名称
                if (checkInManagement.getNursingLevelId() != null) {
                    NursingLevel nursingLevel = nursingLevelMapper.selectNursingLevelById(checkInManagement.getNursingLevelId());
                    if (nursingLevel != null) {
                        bill.setNursingname(nursingLevel.getLevelName());
                    }
                }
                
                // 4. 从查询结果中获取房间类型名称（已通过join查询出来）
                if (bill.getBed() != null && bill.getBed().getRoom() != null 
                    && bill.getBed().getRoom().getRoomType() != null) {
                    bill.setRoomtype(bill.getBed().getRoom().getRoomType().getRoomType());
                }
            }
        }
        
        return bill;
    }

    /**
     * 查询入账列表列表
     * 
     * @param bill 入账列表
     * @return 入账列表
     */
    @Override
    public List<Bill> selectBillList(Bill bill)
    {
        log.info("查询账单列表参数: billNo={}, name={}, idCard={}, bedNo={}, elderlyId={}, transactionStatus={}, billMonth={}", 
            bill.getBillNo(), bill.getName(), bill.getIdCard(), bill.getBedNo(), 
            bill.getElderlyId(), bill.getTransactionStatus(), bill.getBillMonth());
        List<Bill> billList = billMapper.selectBillList(bill);
        log.info("查询到 {} 条账单记录", billList != null ? billList.size() : 0);
        
        // 记录前3条数据用于调试
        if (billList != null && !billList.isEmpty()) {
            for (int i = 0; i < Math.min(3, billList.size()); i++) {
                Bill b = billList.get(i);
                log.info("账单[{}]: id={}, billNo={}, elderlyId={}, name={}, idCard={}", 
                    i, b.getId(), b.getBillNo(), b.getElderlyId(), b.getName(), b.getIdCard());
                if (b.getElderly() != null) {
                    log.info("  - elderly对象: name={}, idCard={}", b.getElderly().getName(), b.getElderly().getIdCard());
                }
            }
        }
        
        return billList;
    }

    /**
     * 新增入账列表
     * 
     * @param bill 入账列表
     * @return 结果
     */
    @Override
    public int insertBill(Bill bill)
    {
        bill.setCreateTime(DateUtils.getNowDate());
        return billMapper.insertBill(bill);
    }

    /**
     * 修改入账列表
     * 
     * @param bill 入账列表
     * @return 结果
     */
    @Override
    public int updateBill(Bill bill)
    {
        // 如果账单被置为已支付，则从对应老人的预交款余额中扣减应付金额
        if (bill.getTransactionStatus() != null && "已支付".equals(bill.getTransactionStatus())) {
            if (bill.getElderlyId() != null && bill.getPayableAmount() != null) {
                // 扣减余额；余额不足等规则可在调用处或数据库层约束
                balanceMapper.deductPrepaymentByElderlyId(bill.getElderlyId(), bill.getPayableAmount());
            }
        }
        return billMapper.updateBill(bill);
    }

    /**
     * 批量删除入账列表
     * 
     * @param ids 需要删除的入账列表主键
     * @return 结果
     */
    @Override
    public int deleteBillByIds(Long[] ids)
    {
        return billMapper.deleteBillByIds(ids);
    }

    /**
     * 删除入账列表信息
     * 
     * @param id 入账列表主键
     * @return 结果
     */
    @Override
    public int deleteBillById(Long id)
    {
        return billMapper.deleteBillById(id);
    }

    /**
     * 手动生成账单（当前月之后的月份）
     * 
     * @param elderlyId 老人ID
     * @param billMonth 账单月份(格式：YYYY-MM)
     * @return 结果
     */
    @Override
    @Transactional
    public int generateBillManually(Long elderlyId, String billMonth)
    {
        log.info("开始手动生成账单, elderlyId={}, billMonth={}", elderlyId, billMonth);
        
        // 1. 验证月份（只能生成当前月之后的月份）
        YearMonth targetMonth = YearMonth.parse(billMonth, DateTimeFormatter.ofPattern("yyyy-MM"));
        YearMonth currentMonth = YearMonth.now();
        
        if (!targetMonth.isAfter(currentMonth)) {
            log.error("只能生成当前月之后的账单，targetMonth={}, currentMonth={}", targetMonth, currentMonth);
            throw new RuntimeException("只能生成当前月之后的月份账单（不包含本月）");
        }
        
        // 2. 检查该老人该月份账单是否已存在（排除已关闭状态的账单）
        Bill checkBill = new Bill();
        checkBill.setElderlyId(elderlyId);
        checkBill.setBillMonth(billMonth);
        List<Bill> existingBills = billMapper.selectBillList(checkBill);
        
        // 检查是否存在非"已关闭"状态的账单
        if (existingBills != null && !existingBills.isEmpty()) {
            boolean hasNonClosedBill = false;
            for (Bill bill : existingBills) {
                // 如果存在非"已关闭"状态的账单，则不允许重复生成
                if (bill.getTransactionStatus() != null && !"已关闭".equals(bill.getTransactionStatus())) {
                    hasNonClosedBill = true;
                    break;
                }
            }
            if (hasNonClosedBill) {
                log.error("该老人在该月份已存在非已关闭状态的账单");
                throw new RuntimeException("该老人在指定月份已存在非已关闭状态的账单，不可重复生成");
            }
        }
        
        // 3. 生成账单
        return generateBillForElderly(elderlyId, billMonth, "月度");
    }

    /**
     * 自动生成下月账单（已入住老人）
     * 
     * @return 生成的账单数量
     */
    @Override
    @Transactional
    public int generateBillsAuto()
    {
        log.info("开始自动生成下月账单");
        
        // 计算下个月
        YearMonth nextMonth = YearMonth.now().plusMonths(1);
        String billMonth = nextMonth.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        
        // 查询所有已入住的老人（通过入住管理表）
        CheckInManagement checkInQuery = new CheckInManagement();
        checkInQuery.setContractStatus("已入住");
        List<CheckInManagement> checkInList = checkInManagementMapper.selectCheckInManagementList(checkInQuery);
        
        if (checkInList == null || checkInList.isEmpty()) {
            log.info("没有已入住的老人，无需生成账单");
            return 0;
        }
        
        int successCount = 0;
        for (CheckInManagement checkIn : checkInList) {
            Long elderlyId = checkIn.getElderlyId();
            if (elderlyId == null) {
                continue;
            }
            
            try {
                // 检查是否已存在账单（排除已关闭状态的账单）
                Bill checkBill = new Bill();
                checkBill.setElderlyId(elderlyId);
                checkBill.setBillMonth(billMonth);
                List<Bill> existingBills = billMapper.selectBillList(checkBill);
                
                // 检查是否存在非"已关闭"状态的账单
                boolean hasNonClosedBill = false;
                if (existingBills != null && !existingBills.isEmpty()) {
                    for (Bill bill : existingBills) {
                        // 如果存在非"已关闭"状态的账单，则不生成新账单
                        if (bill.getTransactionStatus() != null && !"已关闭".equals(bill.getTransactionStatus())) {
                            hasNonClosedBill = true;
                            break;
                        }
                    }
                }
                
                // 只有当不存在账单，或只存在"已关闭"状态的账单时，才生成新账单
                if (!hasNonClosedBill) {
                    generateBillForElderly(elderlyId, billMonth, "月度");
                    successCount++;
                    log.info("为老人ID={}生成{}月份账单成功", elderlyId, billMonth);
                } else {
                    log.info("老人ID={}的{}月份已存在非已关闭状态的账单，跳过生成", elderlyId, billMonth);
                }
            } catch (Exception e) {
                log.error("为老人ID={}生成账单失败", elderlyId, e);
            }
        }
        
        log.info("自动生成账单完成，共生成{}条", successCount);
        return successCount;
    }

    /**
     * 生成首期缴费账单（合同签约时调用）
     * 
     * @param elderlyId 老人ID
     * @return 结果
     */
    @Override
    @Transactional
    public int generateFirstBill(Long elderlyId)
    {
        log.info("开始生成首期缴费账单, elderlyId={}", elderlyId);
        
        // 获取当前月份
        String billMonth = YearMonth.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        
        // 检查是否已存在首期账单
        Bill checkBill = new Bill();
        checkBill.setElderlyId(elderlyId);
        checkBill.setBillMonth(billMonth);
        checkBill.setBillType("首期");
        List<Bill> existingBills = billMapper.selectBillList(checkBill);
        
        if (existingBills != null && !existingBills.isEmpty()) {
            log.warn("首期账单已存在，不重复生成");
            return 0;
        }
        
        // 生成首期账单
        return generateBillForElderly(elderlyId, billMonth, "首期");
    }

    /**
     * 标记欠费账单
     * 
     * @return 标记的账单数量
     */
    @Override
    @Transactional
    public int markOverdueBills()
    {
        log.info("开始标记欠费账单");
        
        // 查询所有待支付且支付截止日期已过期的账单
        Bill queryBill = new Bill();
        queryBill.setTransactionStatus("待支付");
        List<Bill> billList = billMapper.selectBillList(queryBill);
        
        int count = 0;
        Date now = new Date();
        
        for (Bill bill : billList) {
            if (bill.getPaymentDeadline() != null && bill.getPaymentDeadline().before(now)) {
                // 更新账单为欠费状态（使用extra_field1标记）
                Bill updateBill = new Bill();
                updateBill.setId(bill.getId());
                updateBill.setExtraField1("欠费");
                billMapper.updateBill(updateBill);
                count++;
            }
        }
        
        log.info("标记欠费账单完成，共标记{}条", count);
        return count;
    }

    /**
     * 为指定老人生成账单（核心方法）
     * 
     * @param elderlyId 老人ID
     * @param billMonth 账单月份
     * @param billType 账单类型
     * @return 结果
     */
    private int generateBillForElderly(Long elderlyId, String billMonth, String billType)
    {
        log.info("为老人生成账单, elderlyId={}, billMonth={}, billType={}", elderlyId, billMonth, billType);
        
        // 1. 查询老人的入住信息
        CheckInManagement checkInManagement = new CheckInManagement();
        checkInManagement.setElderlyId(elderlyId);
        List<CheckInManagement> checkInList = checkInManagementMapper.selectCheckInManagementList(checkInManagement);
        
        if (checkInList == null || checkInList.isEmpty()) {
            log.error("未找到老人的入住信息");
            throw new RuntimeException("未找到老人的入住信息");
        }
        
        CheckInManagement checkIn = checkInList.get(0);
        
        // 2. 计算账单金额
        BillCalculateResult result = calculateBillAmount(checkIn, billMonth, billType);
        
        // 3. 获取护理等级名称和床位号
        String nursingLevelName = null;
        String bedNo = null;
        
        log.info("查询护理等级和床位信息 - nursingLevelId={}, bedId={}", 
            checkIn.getNursingLevelId(), checkIn.getBedId());
        
        if (checkIn.getNursingLevelId() != null) {
            NursingLevel nursingLevel = nursingLevelMapper.selectNursingLevelById(checkIn.getNursingLevelId());
            if (nursingLevel != null) {
                nursingLevelName = nursingLevel.getLevelName();
                log.info("查询到护理等级: {}", nursingLevelName);
            } else {
                log.warn("未查询到护理等级，nursingLevelId={}", checkIn.getNursingLevelId());
            }
        } else {
            log.warn("入住信息中护理等级ID为空");
        }
        
        if (checkIn.getBedId() != null) {
            Bed bed = bedMapper.selectBedById(checkIn.getBedId());
            if (bed != null) {
                bedNo = bed.getBedNo();
                log.info("查询到床位号: {}", bedNo);
            } else {
                log.warn("未查询到床位，bedId={}", checkIn.getBedId());
            }
        } else {
            log.warn("入住信息中床位ID为空");
        }
        
        // 4. 生成账单编号
        String billNo = generateBillNo();
        
        // 5. 创建账单
        Bill bill = new Bill();
        bill.setBillNo(billNo);
        bill.setBillType(billType);
        bill.setBillMonth(billMonth);
        bill.setElderlyId(elderlyId);
        bill.setMonthlyPayable(result.monthlyPayable);
        bill.setCurrentPayable(result.currentPayable);
        bill.setPrepaymentAmount(BigDecimal.ZERO); // 预交款支付金额初始为0
        bill.setBillAmount(result.billAmount);
        bill.setPayableAmount(result.payableAmount);
        
        // 设置支付截止日期（当月5号）
        YearMonth targetMonth = YearMonth.parse(billMonth, DateTimeFormatter.ofPattern("yyyy-MM"));
        LocalDate deadlineDate = targetMonth.atDay(5);
        bill.setPaymentDeadline(Date.from(deadlineDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        
        bill.setTransactionStatus("待支付");
        
        // 设置账单开始和结束时间
        LocalDate startDate = targetMonth.atDay(1);
        LocalDate endDate = targetMonth.atEndOfMonth();
        bill.setBillStartTime(Date.from(startDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        bill.setBillEndTime(Date.from(endDate.atStartOfDay(ZoneId.systemDefault()).toInstant()));
        
        bill.setCreateTime(new Date());
        
        // 设置创建人
        try {
            bill.setCreator(SecurityUtils.getUserId());
        } catch (Exception e) {
            log.warn("获取当前用户ID失败，可能是系统自动任务调用", e);
            // 如果是系统自动任务，则不设置创建人
        }
        
        // 6. 保存账单
        int insertResult = billMapper.insertBill(bill);
        
        // 7. 生成账单详情
        if (insertResult > 0) {
            generateBillDetails(bill.getId(), result, nursingLevelName, bedNo);
        }
        
        log.info("账单生成成功, billId={}", bill.getId());
        return insertResult;
    }

    /**
     * 计算账单金额
     */
    private BillCalculateResult calculateBillAmount(CheckInManagement checkIn, String billMonth, String billType)
    {
        BillCalculateResult result = new BillCalculateResult();
        
        // 获取护理费用、床位费用等
        // 优先从check_in_management获取，如果为空则从关联表查询
        BigDecimal nursingFee = checkIn.getNursingFee();
        BigDecimal bedFee = checkIn.getBedFee();
        
        // 如果nursingFee为空，从护理等级表查询
        if (nursingFee == null && checkIn.getNursingLevelId() != null) {
            NursingLevel nursingLevel = nursingLevelMapper.selectNursingLevelById(checkIn.getNursingLevelId());
            if (nursingLevel != null && nursingLevel.getNursingFee() != null) {
                nursingFee = nursingLevel.getNursingFee();
                log.info("从护理等级表查询到护理费用: {}", nursingFee);
            }
        }
        
        // 最终兜底为0
        nursingFee = nursingFee != null ? nursingFee : BigDecimal.ZERO;
        bedFee = bedFee != null ? bedFee : BigDecimal.ZERO;
        
        BigDecimal otherFee = checkIn.getOtherFee() != null ? checkIn.getOtherFee() : BigDecimal.ZERO;
        BigDecimal medicalInsurance = checkIn.getMedicalInsurancePayment() != null ? checkIn.getMedicalInsurancePayment() : BigDecimal.ZERO;
        BigDecimal govSubsidy = checkIn.getGovernmentSubsidy() != null ? checkIn.getGovernmentSubsidy() : BigDecimal.ZERO;
        BigDecimal deposit = checkIn.getDeposit() != null ? checkIn.getDeposit() : BigDecimal.ZERO;
        
        // 每月应付 = (护理费用 + 床位费用 + 其他费用) - (医保支付 + 政府补贴)
        BigDecimal addItems = nursingFee.add(bedFee).add(otherFee);
        BigDecimal deductItems = medicalInsurance.add(govSubsidy);
        result.monthlyPayable = addItems.subtract(deductItems).setScale(2, RoundingMode.HALF_UP);
        
        // 本期应付计算
        if ("首期".equals(billType)) {
            // 首期：从入住日期到月底的天数比例
            result.currentPayable = calculateProRatedAmount(checkIn, billMonth, result.monthlyPayable);
        } else {
            // 月度：整月
            result.currentPayable = result.monthlyPayable;
        }
        
        // 账单金额 = 本期应付 + 押金（仅首期）
        if ("首期".equals(billType)) {
            result.billAmount = result.currentPayable.add(deposit).setScale(2, RoundingMode.HALF_UP);
        } else {
            result.billAmount = result.currentPayable.setScale(2, RoundingMode.HALF_UP);
        }
        
        // 应付金额 = 账单金额 - 预交款金额（这里预交款为0，实际支付时从余额扣）
        result.payableAmount = result.billAmount;
        
        // 保存费用明细用于生成账单详情
        result.nursingFee = nursingFee;
        result.bedFee = bedFee;
        result.otherFee = otherFee;
        result.medicalInsurance = medicalInsurance;
        result.govSubsidy = govSubsidy;
        result.deposit = deposit;
        
        return result;
    }

    /**
     * 计算按比例的金额（用于首期账单）
     */
    private BigDecimal calculateProRatedAmount(CheckInManagement checkIn, String billMonth, BigDecimal monthlyAmount)
    {
        if (checkIn.getCheckInStartTime() == null) {
            return monthlyAmount;
        }
        
        try {
            LocalDate checkInDate = checkIn.getCheckInStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            YearMonth targetMonth = YearMonth.parse(billMonth, DateTimeFormatter.ofPattern("yyyy-MM"));
            LocalDate monthStart = targetMonth.atDay(1);
            LocalDate monthEnd = targetMonth.atEndOfMonth();
            
            // 如果入住日期不在目标月份，返回整月金额
            if (checkInDate.isBefore(monthStart) || checkInDate.isAfter(monthEnd)) {
                return monthlyAmount;
            }
            
            // 计算从入住日到月底的天数
            long daysInPeriod = ChronoUnit.DAYS.between(checkInDate, monthEnd) + 1;
            long daysInMonth = targetMonth.lengthOfMonth();
            
            // 本期应付 = 共计天数 / 该月份总天数 * 每月应付
            return monthlyAmount.multiply(BigDecimal.valueOf(daysInPeriod))
                    .divide(BigDecimal.valueOf(daysInMonth), 2, RoundingMode.HALF_UP);
        } catch (Exception e) {
            log.error("计算按比例金额失败", e);
            return monthlyAmount;
        }
    }

    /**
     * 生成账单详情
     */
    private void generateBillDetails(Long billId, BillCalculateResult result, String nursingLevelName, String bedNo)
    {
        List<BillDetail> details = new ArrayList<>();
        
        // 添加项
        if (result.nursingFee.compareTo(BigDecimal.ZERO) > 0) {
            BillDetail detail = new BillDetail();
            detail.setBillId(billId);
            detail.setType("添加项");
            detail.setItemName("护理费用");
            // 使用护理等级名称作为服务内容，如果为空则使用默认值
            detail.setServiceContent(nursingLevelName != null ? nursingLevelName : "—");
            detail.setAmount(result.nursingFee);
            details.add(detail);
        }
        
        if (result.bedFee.compareTo(BigDecimal.ZERO) > 0) {
            BillDetail detail = new BillDetail();
            detail.setBillId(billId);
            detail.setType("添加项");
            detail.setItemName("床位费用");
            // 使用床位号作为服务内容，如果为空则使用默认值
            detail.setServiceContent(bedNo != null ? bedNo : "—");
            detail.setAmount(result.bedFee);
            details.add(detail);
        }
        
        if (result.otherFee.compareTo(BigDecimal.ZERO) > 0) {
            BillDetail detail = new BillDetail();
            detail.setBillId(billId);
            detail.setType("添加项");
            detail.setItemName("其他费用");
            detail.setServiceContent("其他服务");
            detail.setAmount(result.otherFee);
            details.add(detail);
        }
        
        // 扣减项
        if (result.medicalInsurance.compareTo(BigDecimal.ZERO) > 0) {
            BillDetail detail = new BillDetail();
            detail.setBillId(billId);
            detail.setType("扣减项");
            detail.setItemName("医保支付");
            detail.setServiceContent("医保");
            detail.setAmount(result.medicalInsurance);
            details.add(detail);
        }
        
        if (result.govSubsidy.compareTo(BigDecimal.ZERO) > 0) {
            BillDetail detail = new BillDetail();
            detail.setBillId(billId);
            detail.setType("扣减项");
            detail.setItemName("政府补贴");
            detail.setServiceContent("政府养老服务补贴");
            detail.setAmount(result.govSubsidy);
            details.add(detail);
        }
        
        // 保存所有详情
        for (BillDetail detail : details) {
            billDetailService.insertBillDetail(detail);
        }
    }

    /**
     * 生成账单编号
     */
    private String generateBillNo()
    {
        return "BILL" + System.currentTimeMillis();
    }

    /**
     * 账单计算结果内部类
     */
    private static class BillCalculateResult
    {
        BigDecimal monthlyPayable = BigDecimal.ZERO;   // 每月应付
        BigDecimal currentPayable = BigDecimal.ZERO;   // 本期应付
        BigDecimal billAmount = BigDecimal.ZERO;       // 账单金额
        BigDecimal payableAmount = BigDecimal.ZERO;    // 应付金额
        
        // 费用明细
        BigDecimal nursingFee = BigDecimal.ZERO;
        BigDecimal bedFee = BigDecimal.ZERO;
        BigDecimal otherFee = BigDecimal.ZERO;
        BigDecimal medicalInsurance = BigDecimal.ZERO;
        BigDecimal govSubsidy = BigDecimal.ZERO;
        BigDecimal deposit = BigDecimal.ZERO;
    }

    @Override
    public int getElderlyCountForBillGeneration()
    {
        try {
            CheckInManagement checkInQuery = new CheckInManagement();
            checkInQuery.setContractStatus("已入住");
            List<CheckInManagement> checkInList = checkInManagementMapper.selectCheckInManagementList(checkInQuery);
            return checkInList != null ? checkInList.size() : 0;
        } catch (Exception e) {
            log.error("获取已入住老人数量失败", e);
            return 0;
        }
    }

    @Override
    public int getExistingBillCount(String billMonth)
    {
        try {
            Bill queryBill = new Bill();
            queryBill.setBillMonth(billMonth);
            queryBill.setBillType("月度");
            List<Bill> existingBills = billMapper.selectBillList(queryBill);
            return existingBills != null ? existingBills.size() : 0;
        } catch (Exception e) {
            log.error("获取已存在账单数量失败", e);
            return 0;
        }
    }
}
